import './login.less'
import React, { useEffect, useState, useRef } from 'react'
import { message } from 'antd'
import { Form, Input, Button, Picker, InputItem } from 'antd-mobile'
import { useDispatch } from 'react-redux'
import { store } from '@/reducer'
import { ztLogin, setUserInfo, setDeptInfo } from '@/reducer/getters/user'
import { getLoginInfo, getDeptInfo, getHosInfo, GetTime, GetProject } from '@/api/login'
import { useNavigate } from 'react-router-dom'
import { globalConfig } from '@/globalConfig'
import md5 from 'js-md5'
import _ from '@libs/lodash'
import { setStorage } from '@libs/storage'
import RcUtils from '@/libs/rc4.js'

const { PROJECT_TITLE } = globalConfig
const LoginPage = () => {
	const navigate = useNavigate()
	// 获取redux派发钩子
	const dispatch = useDispatch()

	const inputRef = useRef(null)

	const [hoscodeOptions, setHoscodeOptions] = useState([])
	const [hoscodeVisible, setHoscodeVisible] = useState(false)
	const [hoscodeName, setHoscodeName] = useState('')
	const [deptOptions, setDeptOptions] = useState([])
	const [deptVisible, setDeptVisible] = useState(false)
	const [deptName, setDeptName] = useState('')
	const [form] = Form.useForm()
	useEffect(() => {
		init().then(() => {
			getHosInfo({ 参数: [{ hoscode: '#null' }] }).then(res => {
				const result = res.DATA || []
				result.map(line => {
					line.label = line.HOSNAME
					line.value = line.HOSCODE
				})
				setHoscodeOptions(result)
			})
		})
	}, [])

	// 加载执行 获取token
	const init = () => {
		// return new Promise(resolve => {
		// 	const ztLoginquery = {
		// 		参数: [
		// 			{ 参数名: '用户', 参数值: 'admin' },
		// 			{ 参数名: '密码 ', 参数值: md5('123456') }
		// 		]
		// 	}
		// 	dispatch(ztLogin(ztLoginquery)).then(() => {
		// 		resolve()
		// 	})
		// })
		return new Promise(resolve => {
			GetProject().then(res => {
				const DATA = res.DATA
				const result = DATA.split('|')
				GetTime().then(time_res => {
					const mwToken = `9|${time_res}|SYSTEMTOKEN|99|${time_res}`
					const projcec_res = md5(result[0]).toUpperCase()
					const str = projcec_res.substring(8, 24).toUpperCase()
					const arr = RcUtils.rc4(str, mwToken)
					let token = RcUtils.byteArrayToHex(arr).toUpperCase()
					dispatch(ztLogin({ token, mwToken })).then(() => {
						resolve()
					})
				})
			})
		})
	}

	// 选择院区 获取部门
	const changeHosCode = e => {
		return new Promise(resolve => {
			form.setFieldValue('deptid', '')
			if (_.isEmpty(e)) {
				setDeptOptions([])
				resolve()
			} else {
				const deptQuery = {
					参数: [
						{
							useflag: '1',
							hoscode: e
						}
					]
				}
				getDeptInfo(deptQuery).then(res => {
					const { DATA = [] } = res
					if (DATA.length > 0) {
						const list = _.cloneDeep(DATA)
						list.map(line => {
							line.label = line.DEPTNAME
							line.value = line.DEPTID
						})
						setDeptOptions(list)
						resolve(list)
					} else {
						setDeptOptions([])
						resolve([])
					}
				})
			}
		})
	}

	const onPressEnter = e => {
		form.setFieldValue('hoscode', '')
		setHoscodeName('')
		form.setFieldValue('deptid', '')
		setDeptName('')
		const infoQuery = {
			参数: [{ empid: e.target.value }]
		}
		getLoginInfo(infoQuery).then(res => {
			const result = res.DATA || []
			if (result.length > 0) {
				const userInfo = result[0]
				const { HOSCODE, DEPTID } = userInfo
				const hoscodeItem = hoscodeOptions.find(item => item.value === HOSCODE)
				if (hoscodeItem) {
					form.setFieldValue('hoscode', HOSCODE)
					setHoscodeName(hoscodeItem.label)
					changeHosCode(HOSCODE).then(list => {
						const deptItem = list.find(item => item.value === DEPTID)
						if (deptItem) {
							form.setFieldValue('deptid', DEPTID)
							setDeptName(deptItem.label)
							inputRef.current.focus()
						}
					})
				}
			}
		})
	}

	// 需求逻辑
	// 默认走中台的登录获取授权码   ---后期替换成从程序获取 Authorization
	// 选择院区  执行执行getDept接口  获取科室的值集
	// 名称empid输入 回车或者密码 执行getInfo接口  获取用户信息密码 校验密码是否正确
	//  登录成功  选择的科室 和用户信息 缓存到全局

	const onFinish = () => {
		console.log(form.getFieldsValue())
		const { hoscode, deptid, empid, password } = form.getFieldsValue()
		if (!empid) {
			message.error('请输入账号')
			return
		}
		if (!hoscode) {
			message.error('请选择院区')
			return
		}
		if (!deptid) {
			message.error('请选择科室')
			return
		}
		if (!password) {
			message.error('请输入密码')
			return
		}
		const infoQuery = {
			参数: [{ hoscode, empid }]
		}
		getLoginInfo(infoQuery).then(info_res => {
			const { DATA = [] } = info_res
			if (DATA.length > 0) {
				const userInfo = DATA[0]
				if (userInfo.PASSWORD !== password) {
					message.error('用户密码输入错误')
					return
				}
				const deptInfo = deptOptions.find(item => item.value === deptid)
				store.dispatch(setUserInfo(userInfo))
				store.dispatch(setDeptInfo(deptInfo))
				setStorage('BGKJ_INFO', { userInfo, deptInfo })
				navigate('/home')
			} else {
				message.error('没有查到对应的用户信息')
			}
		})
	}

	return (
		<div className="P-login">
			<div className="P-title">{PROJECT_TITLE}</div>
			<div className="login">
				<Form className="login-form" autoComplete="off" form={form} preserve={false}>
					<Form.Item label="账号" name="empid">
						<Input placeholder="请输入账号" onEnterPress={e => onPressEnter(e)} onBlur={e => onPressEnter(e)} />
					</Form.Item>
					<Form.Item
						label="院区"
						name="hoscode"
						placeholder="请选择院区"
						trigger="onConfirm"
						onClick={e => {
							setHoscodeVisible(true)
						}}
					>
						<Picker
							columns={[hoscodeOptions]}
							visible={hoscodeVisible}
							onClose={() => {
								setHoscodeVisible(false)
							}}
							value={form.getFieldValue('hoscode')}
							onConfirm={v => {
								const hoscodeItem = hoscodeOptions.find(item => item.value === v[0])
								if (hoscodeItem) {
									setHoscodeName(hoscodeItem.label)
								}
								changeHosCode(v[0])
								form.setFieldValue('hoscode', v[0])
							}}
						></Picker>
						<Input placeholder="请输入内容" value={hoscodeName} readOnly />
					</Form.Item>
					<Form.Item
						label="科室"
						name="deptid"
						placeholder="请选择科室"
						trigger="onConfirm"
						onClick={e => {
							if (deptOptions.length > 0) {
								setDeptVisible(true)
							}
						}}
					>
						<Picker
							columns={[deptOptions]}
							visible={deptVisible}
							onClose={() => {
								setDeptVisible(false)
							}}
							value={form.getFieldValue('deptid')}
							onConfirm={v => {
								const deptItem = deptOptions.find(item => item.value === v[0])
								if (deptItem) {
									setDeptName(deptItem.label)
								}
								form.setFieldValue('deptid', v[0])
							}}
						></Picker>
						<Input placeholder="请输入内容" value={deptName} readOnly />
					</Form.Item>

					<Form.Item label="密码" name="password">
						<Input type="password" ref={inputRef} placeholder="请输入密码" onPressEnter={() => onFinish()} />
					</Form.Item>
					<Form.Item wrapperCol={{ span: 24 }}>
						<Button block color="primary" size="large" onClick={() => onFinish()}>
							登录
						</Button>
					</Form.Item>
				</Form>
			</div>
		</div>
	)
}

export default LoginPage
